<?php
namespace App\Common\ScarecrowProvider;

use App\Models\AuthManage\LoginModel;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\DB;

/**
 * Scarecrow自己做的Auth管理器
 * Class ScarecrowAuthProvider
 * @package App\Common\ScarecrowProvider
 */
class ScarecrowAuthProvider {
	/**
	 * 获取当前用户ID
	 * @param string $token
	 * @return bool|mixed
	 */
	public function id($token = '') {
		$userInfo = $this->user($token);
		if ($userInfo) {
			return $userInfo['id'];
		}
		return false;
	}

	/**
	 * 获取用户信息
	 * @param string $token
	 * @return bool
	 */
	public function user($token = '') {
		$token = $token ?: (defined('APP_USER_TOKEN') ? APP_USER_TOKEN : "");
		$userInfoObj = LoginModel::getUserInfo($token);
		if ($userInfoObj['code'] == 0) {
			return $userInfoObj['data'];
		}
		return false;
	}

	/**
	 * 退出登录
	 * @param string $token
	 * @return bool
	 */
	public function logout($token = '') {
		$token = $token ?: (defined('APP_USER_TOKEN') ? APP_USER_TOKEN : "");
		LoginModel::LoginOut($token);
		return true;
	}

	/**
	 * 加密用户密码
	 * @param $userPassword
	 * @return string
	 */
	public function CryptPassword($userPassword) {
		return LoginModel::CryptPassword($userPassword);
	}

	/**
	 * 判断用户是否是超级管理员
	 * @param string $token
	 * @return bool
	 */
	public function isAdmin($token = '') {
		$token = $token ?: (defined('APP_USER_TOKEN') ? APP_USER_TOKEN : "");
		$userInfoObj = LoginModel::getUserInfo($token, 'is_supper_admin');
		if ($userInfoObj['code'] == 0) {
			return (bool)$userInfoObj['data'];
		}
		return false;
	}

    /**
     * 当前用户时候有权限编辑当前项目
     * @param $projectId
     * @param string $token
     * @return bool
     */
	public function hasAuthEditProject($projectId, $token = '') {
        if ($this->isAdmin($token)) {
            return true;
        }

        $userId = $this->id($token);
        $CacheName = 'API_AUTH_EDIT_USER_' . $userId . "_" . $projectId;
        if (Cache::has($CacheName)) {
            $nowUserViewAuth = Cache::get($CacheName, []);
            if ($nowUserViewAuth) {
                if ($nowUserViewAuth['isAllProjectManage'] ?? "") {
                    return true;
                }

                if ($nowUserViewAuth['isProjectManage'] ?? "") {
                    return true;
                }

                return false;
            }
        }

        $nowUserViewAuth = [];
        $isAllProjectManage = DB::table('sc_user_all_project_auth')->where("user_id", $userId)->first();
		$isAllProjectManage = DbObjectToArr($isAllProjectManage);
        if ($isAllProjectManage && $isAllProjectManage['write']) {
            $nowUserViewAuth['isAllProjectManage'] = 1;
            Cache::add($CacheName, $nowUserViewAuth, 86400);
            return true;
        }
        $nowUserViewAuth['isAllProjectManage'] = 0;

        $isProjectManage = DB::table('sc_user_project_auth')->where(['user_id'=>$userId, 'project_id'=>$projectId])->first();

		$isProjectManage = DbObjectToArr($isProjectManage);
        if ($isProjectManage && $isProjectManage['write']) {
            $nowUserViewAuth['isProjectManage'] = 1;
            Cache::add($CacheName, $nowUserViewAuth, 86400);
            return true;
        }

        $nowUserViewAuth['isProjectManage'] = 0;
        Cache::add($CacheName, $nowUserViewAuth, 86400);
        return false;
    }

    /**
     * 检测当前用户是否能查看当前API
     * @param $apiId
     * @param string $token
     * @return bool
     */
    public function hasAuthViewProject($apiId, $token = '') {
        if ($this->isAdmin($token)) {
            return true;
        }

		$apiObj = DB::table('sc_api_doc')->where('id', $apiId)->first();
		if (!$apiObj) {
			return false;
		}
		$apiObj = DbObjectToArr($apiObj);
		$projectId = $apiObj['project_id'];
        $userId = $this->id($token);
        $CacheName = 'API_AUTH_VIEW_USER_' . $userId . "_" . $projectId;
        if (Cache::has($CacheName)) {
            $nowUserViewAuth = Cache::get($CacheName, []);
            if ($nowUserViewAuth) {
                if ($nowUserViewAuth['isAllProjectManage'] ?? "") {
                    return true;
                }

                if ($nowUserViewAuth['isProjectManage'] ?? "") {
                    return true;
                }

                if (in_array($apiId, $nowUserViewAuth['allProjectApiList'] ?? [])) {
                    return true;
                }

                return false;
            }
        }

        $projectId = $apiObj['project_id'];
        $nowUserViewAuth = [];

        $isAllProjectManage = DB::table('sc_user_all_project_auth')->where("user_id", $userId)->first();
        if ($isAllProjectManage ) {
            $nowUserViewAuth['isAllProjectManage'] = 1;
            Cache::add($CacheName, $nowUserViewAuth, 86400);
            return true;
        }
        $nowUserViewAuth['isAllProjectManage'] = 0;

        $isProjectManage = DB::table('sc_user_project_auth')->where(['user_id'=>$userId, 'project_id'=>$projectId])->first();
        if ($isProjectManage) {
            $nowUserViewAuth['isProjectManage'] = 1;
            Cache::add($CacheName, $nowUserViewAuth, 86400);
            return true;
        }
        $nowUserViewAuth['isProjectManage'] = 0;

        $allProjectApiList = DB::table('sc_user_read_api_doc as t1')->leftJoin('sc_api_doc as t2', 't1.api_doc_id',  '=', 't2.id')->whereRaw("t1.user_id=? AND t2.project_id=?", [$userId, $projectId])->pluck("t1.api_doc_id")->toArray();
        $nowUserViewAuth['allProjectApiList'] = $allProjectApiList;
        Cache::add($CacheName, $nowUserViewAuth, 86400);
        if (in_array($apiId, $allProjectApiList)) {
            return true;
        }

        return false;
    }
}